package com.vietjetair.common;


import com.vietjetair.config.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Service
public class RedisService {

    private static final Logger logger = LogUtils.getExceptionLogger();

    @Resource
    private RedisTemplate redisTemplate;

    private final Object object = new Object();

    /**
     * 批量删除对应的value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 设置有效期
     *
     * @param key        失效key
     * @param expireTime 失效时间,秒数
     * @return
     */
    @SuppressWarnings("unused")
    public boolean expire(final String key, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.expire(key,expireTime, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 返回自增后的值,详细见redis incr命令</br>
     * 若自增前为null,则设置key为1,且返回1</br>
     * !!!!! - 经过改方法,key原本的失效时间会重置 - !!!!!</br>
     * 注意:因为不是原生的incr操作,使用的是set(key,++source),所以会重置过期时间</br>
     * 如果操作的key自带过期时间,如有需要,请在相关逻辑重新设置过期时间,否则经过本方法后key不会过期</br>
     * @param key 自增key
     * @return 返回自增后的值, 若自增前为null,则设置key为1,且返回1
     */
    public Integer incr(String key) {
        Integer index;
        synchronized (object) {
            Object source = this.get(key);
            if (source == null) {//自增前为null,则设置key的对应的值1
                index = 1;
                logger.info("自增出现key不存在,初始化值为1,返回1");
            } else {//否则自增
                index = (Integer) source;
                index++;
            }
            //index为原来的值加1或是1
            this.set(key, index);
        }
        return index;
    }

    /**
     * 同步锁读取缓存
     *
     * @param key key
     * @return value
     */
    public Object syncGet(final String key) {
        Object result;
        synchronized (object) {
            result = this.get(key);
        }
        return result;
    }

    public void sss(int index){
        JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) redisTemplate.getConnectionFactory();
        jedisConnectionFactory.setDatabase(index);
    }


    public void setListValue(String key,Object object){
        List list = null;
        Object doesItExist = this.get(key);
        if (doesItExist==null){
            list = new ArrayList();
            list.add(object);
        }else{
            list = (List) doesItExist;
            list.add(object);
        }
        this.set(key,list);
    }
}
